﻿#region File and License Information
/*
<File>
	<Copyright>Copyright © 2007, Daniel Vaughan. All rights reserved.</Copyright>
	<License see="prj:///Documentation/License.txt"/>
	<Owner Name="Daniel Vaughan" Email="dbvaughan@gmail.com"/>
	<CreationDate>2009-03-29 23:57:55Z</CreationDate>
	<LastSubmissionDate>$Date: $</LastSubmissionDate>
	<Version>$Revision: $</Version>
</File>
*/
#endregion

using System;
using System.Collections.Generic;
using System.Reflection;

using Microsoft.Practices.Unity;

namespace DanielVaughan.DependencyInjection
{
	public static class UnityExtensions
	{
		public static void RegisterDefault<T>(this IUnityContainer container) where T : class
		{
			var types = Assembly.GetExecutingAssembly().GetTypes();
			RegisterDefault<T>(container, types, false);
		}

		public static void RegisterDefaultSingleton<T>(this IUnityContainer container) where T : class
		{
			var types = Assembly.GetExecutingAssembly().GetTypes();
			RegisterDefault<T>(container, types, true);
		}

		static void RegisterDefault<T>(IUnityContainer container, IEnumerable<Type> types, bool singleton)
		{
			foreach (Type type in types)
			{
				Type tType = typeof(T);
				if (!tType.IsAssignableFrom(type) || type.IsInterface)
				{
					continue;
				}
				string className = tType.Name.Substring(1);
				if (type.Name.StartsWith("Default") || type.Name == className)
				{
					if (singleton)
					{
						container.RegisterType(typeof(T), type, new ContainerControlledLifetimeManager());
					}
					else
					{
						container.RegisterType(typeof(T), type);
					}
				}
			}
		}
	}
}
